package com.zwb.aiwebsite.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;

/**
 * @author 2825075112@qq.com
 */
@Slf4j
public class MyStringUtils {

    public static String removeHtmlImg(String str) {
        int i = str.indexOf("<img");

        while (i != -1) {
            int i1 = str.indexOf("/>", i);
            String substring = str.substring(i, i1 + ("/>".length()));
            str = str.replace(substring, "");

            i = str.indexOf("<img");
        }
        return str;
    }

    public static String getWordCount(String str) {
        try {
            String symbol = "...";
            str = removeHtmlImg(str);
            int len = 4 * 100;
            int counterOfDoubleByte = 0;
            byte[] b = str.getBytes("GBK");
            if (b.length <= len)
                return str;
            for (int i = 0; i < len; i++) {
                if (b[i] < 0)
                    counterOfDoubleByte++;
            }
            String result = "";
            if (counterOfDoubleByte % 2 == 0) {
                result = new String(b, 0, len, "GBK").replaceAll("\n", "") + symbol;
            } else {
                result = new String(b, 0, len - 1, "GBK").replaceAll("\n", "") + symbol;
            }

            return result;
        } catch (UnsupportedEncodingException e) {
            log.error("截取字符串getWordCount异常：", e);
            return "";
        }
    }

}
